package com.eorchis.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.swetake.util.Qrcode;

public class BuliderErWeiMa {
	/**
	 * 生成二维码(QRCode)图片
	 * @param content 二维码图片的内容
	 * @param imgPath 生成二维码图片完整的路径
	 * @param ccbpath 二维码图片中间的logo路径
	 * @throws Exception
	 */
	public int createQRCode(String content, String imgPath, String ccbPath, String className, HttpServletRequest request) throws Exception {
		String basePath = PathUtil.getWebRootPath();
		ccbPath = basePath + ccbPath;
		imgPath = basePath + imgPath;
		try {
			Qrcode qrcodeHandler = new Qrcode();
			qrcodeHandler.setQrcodeErrorCorrect('M');
			qrcodeHandler.setQrcodeEncodeMode('B');
			qrcodeHandler.setQrcodeVersion(7);
			// System.out.println(content);
			byte[] contentBytes = content.getBytes("gb2312");
			BufferedImage bufImg = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = bufImg.createGraphics();
			gs.setBackground(Color.WHITE); // 背景颜色
			gs.clearRect(0, 0, 600, 600);
			// 设定图像颜色 > BLACK
			gs.setColor(Color.BLACK); // 条码颜色
			// 设置偏移量 不设置可能导致解析出错
			int pixoff = 2; // 输出内容 > 二维码
			if (contentBytes.length > 0 && contentBytes.length < 200) {
				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * 13 + pixoff, i * 13 + pixoff, 15, 15);
						}
					}
				}
			} else {
				System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,200]. ");
				return -1;
			}

			Image img = ImageIO.read(new File(ccbPath));
			// 实例化一个Image对象。
			int centerX = bufImg.getMinX() + bufImg.getWidth()/2 - 130/2;
	        int centerY = bufImg.getMinY() + bufImg.getHeight()/2 - 130/2;
			gs.drawImage(img, centerX, centerY, 130, 130, null);
			gs.dispose();
			bufImg.flush();
			// 生成二维码QRCode图片
			File imgFile = new File(imgPath, "" + className + ".png");
			ImageIO.write(bufImg, "png", imgFile);
		} catch (Exception e) {
			e.printStackTrace();
			return -100;
		}
		return 0;
	}
}
